package com.gemptc.waimai.web;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.IOException;
import java.text.AttributedCharacterIterator;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class RandServlet
 */
@WebServlet("/RandServlet")
public class RandServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("content-type", "image/jpeg");
		response.setHeader("cache-control", "no-cache");
		response.setHeader("pragma", "no-cache");
		response.setHeader("expires", "-1");
		BufferedImage bf=new BufferedImage(40, 20, BufferedImage.TYPE_INT_RGB);
		Graphics g=bf.getGraphics();
		g.setColor(Color.decode("#66CCCF"));
		g.fillRect(0, 0, 40, 20);
		g.setColor(Color.decode("#01556B"));
		String s=GenerateString();
		HttpSession session = request.getSession();
		session.setAttribute("rand", s);
		g.drawString(s, 5, 15);;
		ImageIO.write(bf, "jpg", response.getOutputStream());
		
	}

	private String GenerateString() {
		Random r=new Random();
		char c1 = (char)('0'+r.nextInt(10));
		String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz";
		char c2 = s.charAt(r.nextInt(52));
		char c3 = (char)('0'+r.nextInt(10));
		char c4 = s.charAt(r.nextInt(52));
		return ""+c1+c2+c3+c4;
	}

}
